package one.stand.controller.index;

import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.jmp.api.dto.*;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.DynamicApi;
import com.jmp.base.UserApi;
import com.jmp.base.dto.*;
import com.jmp.feign.AccountFeign;
import com.jmp.feign.DynamicFeign;
import com.jmp.feign.SeeRecordFeign;
import com.jmp.feign.UserFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import one.stand.advice.ResultEnum;
import one.stand.dto.*;
import one.stand.enums.LoginEnum;
import one.stand.mapper.DynamicMapperExt;
import one.stand.model.BusinessCard;
import one.stand.model.Dynamic;
import one.stand.model.ResultModel;
import one.stand.service.BusinessCardBaseService;
import one.stand.service.CompanyBaseService;
import one.stand.service.RecordPublicService;
import one.stand.service.sys.SysDictValueService;
import one.stand.service.user.UserAdminService;
import one.stand.util.*;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@Api(description = "首页-红木圈(动态、评论、点赞)")
@RestController
@RequestMapping("dynamic")
public class DynamicController {
    @Autowired
    private SeeRecordFeign seeRecordFeign;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private DynamicFeign dynamicFeign;
    @Autowired
    private AccountFeign accountFeign;

    @Autowired
    private SysDictValueService sysDictValueService;
    @Autowired
    private UserAdminService userAdminService;
    @Autowired
    private CompanyBaseService companyBaseService;
    @Autowired
    private RecordPublicService recordPublicService;
    @Autowired
    private DynamicMapperExt dynamicMapperExt;
    @Autowired
    private BusinessCardBaseService businessCardBaseService;

    @ApiOperation(value = "1动态: 列表(分页)")
    @GetMapping("/list")
    public ResultModel<DynamicResponse> list(@RequestAttribute PageRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();
        final boolean isLogin = Objects.nonNull(optUser);

        if (isLogin && request.getPageNum() == 1) {
            userFeign.viewSave(UserViewSaveDto.builder().userId(optUser.getUserId()).type(UserApi.VIEW_TYPE_DYNAMIC).build());
        }

        DynamicListDto dynamicListDto = DynamicListDto.builder().build();
        dynamicListDto.setPageNum(request.getPageNum());
        dynamicListDto.setPageSize(request.getPageSize());
        ResultModel<DynamicListVo> resultModel = dynamicFeign.list(dynamicListDto);
        AssertUtil.isTrue(resultModel);

        PageResponse2<DynamicResponse.Dynamic> dynamicPageResponse2 = ConvertUtils.page2(resultModel.getData().getDynamics(), dynamic -> {

            UserDto user = userAdminService.get(dynamic.getCreateUserId());
            Company2Dto company = companyBaseService.get2(dynamic.getCompanyId());
            BusinessCard card = businessCardBaseService.getByUserId(dynamic.getCreateUserId());

            //最多十条评论
            List<CommentDto> commentDtos = recordPublicService.getCommentList(dynamic.getDynamicId(), 10);
            List<DynamicResponse.Comment> commentResponseList = ConvertUtils.list(commentDtos, commentModel -> {
                return DynamicResponse.Comment.builder()
                        .commentId(commentModel.getCommentId())
                        .userId(commentModel.getUserId())
                        .userName(commentModel.getUserName())
                        .userLogo(OneStringUtils.photoResize(commentModel.getUserLogo()))
                        .content(commentModel.getText())
                        .userChatId(String.valueOf(commentModel.getUserId()))
                        .time(commentModel.getCreateTime().getTime())
                        .build();
            });

            boolean isThumbs = isLogin && recordPublicService.isThumbs(optUser.getUserId(), RecordPublicService.THUMBS_TYPE_ARTICLE, dynamic.getDynamicId());

            return DynamicResponse.Dynamic.builder()
                    .dynamicId(dynamic.getDynamicId())

                    .companyId(company.getCompanyId())
                    .companyName(company.getCompanyName())
                    .companyLogo(company.getCompanyLogo())
                    .companyLevel(company.countCompanyLevelView())
                    .isZk(BooleanUtils.toInteger(companyBaseService.hasZkgx(company.getCompanyId())))

                    .userId(user.getUserId())
                    .userName(user.getName())
                    .userImg(user.getUserImg())
                    .userChatId(String.valueOf(user.getUserId()))
                    .position(Objects.nonNull(card) ? card.getPosition() : null)
                    .userSelfFlag(BooleanUtils.toInteger(isLogin && dynamic.getCreateUserId().equals(optUser.getUserId())))

                    .time(dynamic.getTime())
                    .type(dynamic.getType())
                    .title(dynamic.getTitle())
                    .photos(dynamic.getPhotos())

                    .commentNum(recordPublicService.countCommentByDynamic(dynamic.getDynamicId()))
                    .doThumbsNum(recordPublicService.getThumbsCount(RecordPublicService.THUMBS_TYPE_ARTICLE, dynamic.getDynamicId()))
                    .thumbsImgList(ConvertUtils.list(recordPublicService.getThumbsImgs(RecordPublicService.THUMBS_TYPE_ARTICLE, dynamic.getDynamicId()), thumbsDto -> {
                        return DynamicResponse.Thumbs.builder()
                                .userId(thumbsDto.getUserId())
                                .userName(thumbsDto.getUserName())
                                .userChatId(String.valueOf(thumbsDto.getUserId()))
                                .userImg(OneStringUtils.photoResize(thumbsDto.getUserImg()))
                                .build();
                    }))
                    .thumbsFlag(BooleanUtils.toInteger(isThumbs))
                    .followFlag(BooleanUtils.toInteger(isLogin && recordPublicService.isCollection(optUser.getUserId(), RecordPublicService.ITEMTYPE_USER, dynamic.getCreateUserId())))

                    .commentList(commentResponseList)
                    .build();
        });

        DynamicResponse response = DynamicResponse.builder()
                .dynamics(dynamicPageResponse2)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "2动态: 点赞/取消点赞")
    @PostMapping("/thumbs")
    @SecurityAuthCheck
    public ResultModel<DynamicThumbsResponse> thumbs(@RequestAttribute DynamicThumbsRequest request) {
        AssertUtil.nonNull(request.getDynamicId(), ResultEnum.PARAM_CHECK, "动态ID不能为空");

        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        ResultModel resultModel = userFeign.thumbs(UserThumbsDto.builder()
                .itemType(RecordPublicService.THUMBS_TYPE_ARTICLE)
                .itemId(request.getDynamicId())
                .userId(optUser.getUserId())
                .build());
        AssertUtil.isTrue(resultModel);

        Dynamic dynamic = dynamicMapperExt.selectByPrimaryKey(request.getDynamicId());
        if (!RequestContextHolder.getRequestContext().isSameCompany(dynamic.getCompanyId())) { //添加查看记录
            SeeRecordArticleRequest recordArticleRequest = SeeRecordArticleRequest.builder()
                    .userId(optUser.getUserId())
                    .itemId(request.getDynamicId())
                    .build();
            seeRecordFeign.article(recordArticleRequest);
        }

        UserDto user = userAdminService.get(optUser.getUserId());
        DynamicThumbsResponse response = DynamicThumbsResponse.builder()
                .userName(user.getName())
                .userChatId(String.valueOf(optUser.getUserId()))
                .userImg(OneStringUtils.photoResize(user.getUserImg()))
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "3评论: 查询所有")
    @GetMapping("/comment")
    @SecurityAuthCheck
    public ResultModel<DynamicCommentResponse> comment(@RequestAttribute DynamicCommentRequest request) {
        AssertUtil.nonNull(request.getDynamicId(), ResultEnum.PARAM_CHECK, "动态ID不能为空");
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<CommentDto> commentDtos = recordPublicService.getCommentList(request.getDynamicId(), null);
        PageResponse2<DynamicCommentResponse.Comment> list = ConvertUtils.page2(commentDtos, comment -> {
            return DynamicCommentResponse.Comment.builder()
                    .commentId(comment.getCommentId())
                    .createTime(comment.getCreateTime().getTime())
                    .content(comment.getText())
                    .replyUserName(comment.getReplyName())
                    .userName(comment.getUserName())
                    .userLogo(comment.getUserLogo())
                    .userChatId(String.valueOf(optUser.getUserId()))
                    .build();
        });

        DynamicCommentResponse response = DynamicCommentResponse.builder()
                .list(list)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "3评论: 回复")
    @PostMapping("/comment/save")
    @SecurityAuthCheck
    public ResultModel<DynamicThumbsResponse> commentSave(@RequestAttribute DynamicCommentSaveRequest request) {
        AssertUtil.nonNull(request.getDynamicId(), ResultEnum.PARAM_CHECK, "动态ID不能为空");
        AssertUtil.nonNull(request.getContent(), ResultEnum.PARAM_CHECK, "评论/回复内容不能为空");

        boolean isOn = sysDictValueService.isOn(SysDictValueService.Type.CONFIG, SysDictValueService.TypeName.COMMENT_SWITCH_APP);
        if (isOn) {
            Dynamic dynamic = dynamicMapperExt.selectByPrimaryKey(request.getDynamicId());
            BusinessCard card = businessCardBaseService.getByUserId(dynamic.getCreateUserId());
            RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();
            DynamicCommentSaveDto saveDto = DynamicCommentSaveDto.builder()
                    .commentType(DynamicApi.COMMENT_TYPE_ARTICEL)
                    .dynamicId(request.getDynamicId())
                    .parentId(request.getCommentParentId())
                    .userId(optUser.getUserId())
                    .text(request.getContent())
                    .cardId(card.getCardId())
                    .build();
            ResultModel<DynamicCommentSaveVo> resultModel = dynamicFeign.commentSave(saveDto);
            AssertUtil.isTrue(resultModel);

            UserDto user = userAdminService.get(optUser.getUserId());
            DynamicThumbsResponse response = DynamicThumbsResponse.builder()
                    .commentId(resultModel.getData().getCommentId())
                    .userName(user.getName())
                    .userImg(OneStringUtils.photoResize(user.getUserImg()))
                    .userChatId(String.valueOf(optUser.getUserId()))
                    .build();
            return ResultModel.success(response);
        } else {
            return ResultModel.fail("已提交，审核通过后显示");
        }
    }

    @ApiOperation(value = "3评论: 删除")
    @PostMapping("/comment/remove")
    @SecurityAuthCheck
    public ResultModel commentRemove(@RequestAttribute CommentRemoveRequest request) {
        AssertUtil.nonNull(request.getCommentId(), ResultEnum.PARAM_CHECK, "评论ID不能为空");

        RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        ResultModel resultModel = dynamicFeign.commentRemove(DynamicCommentRemoveDto.builder()
                .commentIds(Lists.newArrayList(request.getCommentId()))
                .userId(optUser.getUserId())
                .build());
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }

    @ApiOperation(value = "4动态:分享")
    @GetMapping("/share")
    @SecurityAuthCheck
    public ResultModel<DynamicShareResponse> share(@RequestAttribute DynamicShareRequest request) {

        Dynamic dynamic = dynamicMapperExt.selectByPrimaryKey(request.getDynamicId());
        BusinessCard card = businessCardBaseService.getByUserId(dynamic.getCreateUserId());

        AccountCompanyIdRequest accountCompanyIdRequest = AccountCompanyIdRequest.builder()
                .companyId(card.getCompanyId())
                .loginEnum(LoginEnum.USER)
                .build();
        ResultModel<AccountResponse> accountResponseResultModel = accountFeign.getCompanyIdDefaultIfNull(accountCompanyIdRequest);
        String wechatId = accountResponseResultModel.isSuccess() ? accountResponseResultModel.getData().getWechatId() : null;

//        TemplateGet2Request getRequest = TemplateGet2Request.builder()
//                .templateType(TemplateApi.Type.ID_ROOM)
//                .cardId(card.getCardId())
//                .roomId(request.getRoomId())
//                .build();
//        ResultModel<TemplateGetResponse> getResponseResultModel = templateFeign.get2(getRequest);
//        AssertUtil.isTrue(getResponseResultModel);
//        String cardUrl = getResponseResultModel.getData().getImageUrl();

        //获取第一张图片
        List<String> photos = StrUtil.split(dynamic.getPhotos(), CharUtil.COMMA);
        String photo = null;
        if (OneListUtil.isNotEmpty(photos)) {
            photo = photos.get(0);
        }

        DynamicShareResponse response = DynamicShareResponse.builder()
                .wechatId(wechatId)
                .title(dynamic.getTitle())
                .photo(photo)
                .path(null)
                .cardUrl(null)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "5动态:详情")
    @GetMapping("/info")
    @SecurityAuthCheck
    public ResultModel<DynamicInfoResponse> info(@RequestAttribute DynamicShareRequest request) {

        Dynamic dynamic = dynamicMapperExt.selectByPrimaryKey(request.getDynamicId());

        //最早三条评论
        List<CommentDto> commentDtos = recordPublicService.getCommentList(dynamic.getDynamicId(), 3);
        List<DynamicInfoResponse.Comment> commentResponseList = ConvertUtils.list(commentDtos, commentModel -> {
            return DynamicInfoResponse.Comment.builder()
                    .userName(commentModel.getUserName())
                    .content(commentModel.getText())
                    .build();
        });

        Company2Dto company = companyBaseService.get2(dynamic.getCompanyId());

        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();
        boolean isThumbs = recordPublicService.isThumbs(optUser.getUserId(), RecordPublicService.THUMBS_TYPE_ARTICLE, dynamic.getDynamicId());

        DynamicInfoResponse response = DynamicInfoResponse.builder()
                .dynamicId(dynamic.getDynamicId())
                .type(dynamic.getType())
                .title(dynamic.getTitle())
                .time(dynamic.getCreateTime().getTime())
                .photos(dynamic.getPhotos())
                .details(dynamic.getDetails())

                .companyId(company.getCompanyId())
                .companyName(company.getCompanyName())
                .companyLogo(company.getCompanyLogo())
                .companyLevel(company.countCompanyLevelView())
                .isZk(BooleanUtils.toInteger(companyBaseService.hasZkgx(company.getCompanyId())))

                .commentList(commentResponseList)

                .commentNum(recordPublicService.countCommentByDynamic(dynamic.getDynamicId()))
                .doThumbsNum(recordPublicService.getThumbsCount(RecordPublicService.THUMBS_TYPE_ARTICLE, dynamic.getDynamicId()))
                .thumbsFlag(BooleanUtils.toInteger(isThumbs))

                .build();
        return ResultModel.success(response);
    }
}
